package com.holly.unit.gen.api.util;

import org.apache.commons.lang3.RandomStringUtils;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 类描述: 随机数工具类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/1/14 14:47
 */
public class RandomUtil {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    private static final String[] zero = {"0","00","0000","00000000"};
    private static Date lastTime;
    private static int count = 0;

    public static String randomStr(int len) {
        return RandomStringUtils.randomAlphanumeric(len);
    }

    public static int randomInt() {
        return new SecureRandom().nextInt();
    }

    public static String randomHexInt() {
        return Integer.toHexString(randomInt());
    }

    public static long randomLong() {
        return new SecureRandom().nextLong();
    }

    public static String randomHexLong() {
        return Long.toHexString(randomLong());
    }

    public static String randomUuid() {
        return UUID.randomUUID().toString();
    }

    public static String currentTimestamp() {
        Date cur = new Date();
        return sdf.format(cur);
    }

    public static long curMills() {
        return System.currentTimeMillis();
    }

    public static String curHexMills() {
        return Long.toHexString(curMills());
    }

    public static synchronized String getCount() {
        Date cur = new Date();
        if (cur.equals(lastTime)) {
            count++;
        } else {
            lastTime = cur;
            count = 0;
        }
        return Integer.toHexString(count);
    }

    public static String format(String src,int len) {
        int spaceLen = len-src.length();
        StringBuilder sb = new StringBuilder();
        while (spaceLen >=8) {
            sb.append(zero[3]);
            spaceLen-=8;
        }
        for (int i=2;i>=0;i--) {
            if ((spaceLen & (1<<i)) !=0) {
                sb.append(zero[i]);
            }
        }
        sb.append(src);
        return sb.toString();
    }


}
